import React, { Component } from 'react'
import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import styles from './index.module.scss'
import img from 'assets/logo.png'
import { login } from 'api/user'
import { setToken } from 'utilis/storage'

class Login extends Component {
  state = {
    // 按钮登陆状态
    loading: false,
  }
  render() {
    return (
      <div className={styles.login}>
        <Card className='login-box'>
          <img
            src={img}
            className='login-logo'
            alt=''
          />
          {/* form表单 */}
          <Form
            size='large'
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              validateTrigger='onBlur'
              name='mobile'
              rules={[
                {
                  required: true,
                  message: '手机号不能为空',
                },
                {
                  pattern: /^1[34578]\d{9}$/,
                  message: '手机号格式不正确',
                },
              ]}
            >
              <Input placeholder='请输入手机号' />
            </Form.Item>

            <Form.Item
              validateTrigger='onBlur'
              name='code'
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式不正确',
                },
              ]}
            >
              <Input placeholder='请输入密码' />
            </Form.Item>

            <Form.Item
              valuePropName='checked'
              name='agree'
              rules={[
                {
                  validator: (rule, value) => (value ? Promise.resolve() : Promise.reject(new Error('请同意协议'))),
                },
              ]}
            >
              <Checkbox>是否同意用户协议</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button
                type='primary'
                htmlType='submit'
                block
                loading={this.state.loading}
              >
                登陆
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  onFinish = async ({ mobile, code }) => {
    this.setState({ loading: true })
    try {
      const { data } = await login(mobile, code)
      message.success('登陆成功', 1, () => {
        setToken(data.token)
        console.log(this.props)
        const { state } = this.props.location
        state ? this.props.history.push(state.from) : this.props.history.push('/home')
        console.log(state.from)
      })
    } catch (error) {
      message.error(error.response.data.message, 1, () => {
        this.setState({ loading: false })
      })
    }
  }
}
export default Login
